﻿using System;
using System.ComponentModel;
using System.IO;
using System.Linq;
using SpectrumAnalyser.ModelObjects;
using SpectrumAnalyser.Shell.ViewModels;

namespace SpectrumAnalyser.Shell.Helpers
{
    public class SpectrumFileProcessorHelper : IDisposable
    {
        private BackgroundWorker _worker;
        private SpectrumFile _model;
        private string _fileName;

        public void ProcessFile(string fileName)
        {
            _fileName = fileName;
            _model = new SpectrumFile();

            _worker = new BackgroundWorker();
            _worker.DoWork += ProcessSpectrumFileStart;
            _worker.RunWorkerCompleted += (sender, args) => OnProcessCompleted(_model);
            _worker.RunWorkerAsync();
        }

        public event ProceFileCompletedEventHandler OnProcessCompleted;

        public delegate void ProceFileCompletedEventHandler(SpectrumFile file);

        private void ProcessSpectrumFileStart(object sender, DoWorkEventArgs doWorkEventArgs)
        {
            var spectrumFile = App.SpectrumFileReader.ReadSpectrumFile(new FileInfo(_fileName));

            WaveletHelper.RoundTwoPower(spectrumFile);

            var connections = App.AppConfigHelper.GetSpectrumDbConnection();

            foreach (var spectrumDbConnectionViewModel in connections)
            {
                //_model =new SpectrumFileViewModel(App.SpectrumPeaksRepository.FillMatchedPeaks(spectrumFile,spectrumDbConnectionViewModel.ToSpectrumDbConnection()));
            }
            _model.DataPoints = spectrumFile.DataPoints;
            _model.FileName = spectrumFile.FileName;
        }

        public void Dispose()
        {
            _worker.Dispose();
        }
    }
}